<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button
          style="float: right"
          @click="handleSearchList()"
          type="primary"
          size="small"
        >
          查询
        </el-button>

        <el-button
          style="float: right; margin-right: 15px"
          @click="handleResetSearch()"
          size="small"
        >
          重置
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form
          :inline="true"
          :model="searchList"
          size="small"
          label-width="140px"
        >
          <el-form-item label="查询起始时间:">
            <el-date-picker
              v-model="searchList.startTime"
              style="width: 203px"
              type="datetime"
              placeholder="选择日期时间"
              clearable
              :default-value="getMonthStartDate()"
            >
            </el-date-picker>
          </el-form-item>

          <el-form-item label="查询结束时间:">
            <el-date-picker
              v-model="searchList.endTime"
              style="width: 203px"
              type="datetime"
              placeholder="选择日期时间"
              clearable
              :default-value="getMonthEndDate()"
            >
            </el-date-picker>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-card style="margin-top: 15px" class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
    </el-card>

    <div class="chart-container">
      <div ref="orderBarChart" class="chart-item"></div>
      <div ref="orderPieChart" class="chart-item"></div>
      <div ref="monthLineChart" class="chart-item"></div>
      <div ref="dayLineChart" class="chart-item"></div>
    </div>

    <!-- <div ref="chart" style="width: 100%; height: 400px">hello</div> -->
  </div>
</template>

<script>
import * as echarts from "echarts";
import moment from "moment";
export default {
  name: "reportData",
  listLoading: false,

  data() {
    return {
      currentDate: new Date(),
      searchList: {
        startTime: "",
        endTime: "",
      },
      countList: {
        receive: "",
        unComplete: "",
        demandNum: "",
        complete: "",
      },
      byDayCountList: [
        {
          sDate: "",
          orderNum: "",
        },
      ],
      byMonthCountList: [
        {
          sDate: "",
          orderNum: "",
        },
      ],
    };
  },
  // mounted() {
  //   this.searchList.startTime = this.getMonthStartDate();
  //   this.searchList.endTime = this.getMonthEndDate();
  // },
  async created() {
    this.searchList.startTime = this.getMonthStartDate();
    this.searchList.endTime = this.getMonthEndDate();
    // console.log(this.searchList.startTime);
    await this.getList();
  },
  methods: {
    getList() {
      this.countTotal(), this.countByDay(), this.countByMonth();
    },
    handleSearchList() {
      this.getList();
    },
    handleResetSearch() {
      this.searchList = {
        startTime: "",
        endTime: "",
      };
    },
    countTotal() {
      this.axios
        .get("/api/company/auth/order/count", {
          params: this.searchList,
        })
        .then((response) => {
          if (response.data.code == "200") {
            this.countList = response.data.value;
            // 订单统计概览
            let orderBarChart = echarts.init(this.$refs.orderBarChart);
            let orderBarChartOption = {
              title: {
                text: "订单概况柱状图",
                left: "center", // 设置标题水平居中
                // textAlign: "center", // 设置标题文字居中
              },
              xAxis: {
                type: "category",
                data: ["已接单", "未完成", "已完成"],
              },
              yAxis: {
                type: "value",
              },
              series: [
                {
                  data: [
                    {
                      value: this.countList.receive,
                      itemStyle: { color: "#5470c6" },
                    },
                    {
                      value: this.countList.unComplete,
                      itemStyle: { color: "#91cc75" },
                    },
                    // {
                    //   value: this.countList.demandNum,
                    //   itemStyle: { color: "#d48265" },
                    // },
                    {
                      value: this.countList.complete,
                      itemStyle: { color: "#fac858" },
                    },
                  ],
                  type: "bar",
                  barWidth: 50,
                  label: {
                    show: true,
                    position: "top",
                    formatter: "{c}",
                  },
                },
              ],
            };
            orderBarChart.setOption(orderBarChartOption);

            let orderPieChart = echarts.init(this.$refs.orderPieChart);
            let orderPieChartOption = {
              title: {
                text: "订单概况饼图",
                left: "center",
                // textAlign: "center", // 设置标题文字居中
              },
              tooltip: {
                trigger: "item",
                formatter: "{a} <br/>{b}: {c} ({d}%)",
              },
              legend: {
                orient: "vertical",
                left: "left",
                data: ["用户下单", "主动接需求"],
              },
              series: [
                {
                  name: "订单概况",
                  type: "pie",
                  radius: ["50%", "70%"],
                  avoidLabelOverlap: false,
                  label: {
                    show: true,
                    position: "outside",
                    formatter: "{c} ({d}%)",
                    fontSize: 14,
                    // position: "center",
                    // fontSize: "30",
                    // fontWeight: "bold",
                  },
                  emphasis: {
                    label: {
                      show: true,
                      fontSize: "30",
                      fontWeight: "bold",
                    },
                  },
                  labelLine: {
                    show: false,
                  },
                  data: [
                    {
                      value: this.countList.receive - this.countList.demandNum,
                      name: "用户下单",
                      itemStyle: { color: "#5182E4" },
                    },
                    // {
                    //   value: this.countList.unComplete,
                    //   name: "未完成",
                    //   // itemStyle: { color: "#f5222d" },
                    // },
                    {
                      value: this.countList.demandNum,
                      name: "主动接需求",
                      itemStyle: { color: "#00BDAE" },
                    },
                    // {
                    //   value: this.countList.complete,
                    //   name: "已完成",
                    //   // itemStyle: { color: "#52c41a" },
                    // },
                  ],
                },
              ],
            };
            orderPieChart.setOption(orderPieChartOption);
          } else {
            this.$message.error(response.data.message);
          }
          // this.listLoading = false;
        })
        .catch((error) => {
          this.$message.error("无法获取概览数据");
          // this.listLoading = false;
        });
    },
    countByDay() {
      // this.listLoading = true;
      this.axios
        .get("/api/company/auth/order/countByDay", {
          params: this.searchList,
        })
        .then((response) => {
          console.log(response);
          if (response.data.code == "200") {
            this.byDayCountList = response.data.value;
            let dayLineChart = echarts.init(this.$refs.dayLineChart);
            let dayLineChartOption = {
              title: {
                text: "按天统计订单数趋势图",
                left: "center",
                // textAlign: "center",
              },
              xAxis: {
                type: "time",
                axisLabel: {
                  formatter: function (value, index) {
                    let date = new Date(value);
                    return (
                      date.getFullYear() +
                      "-" +
                      (date.getMonth() + 1) +
                      "-" +
                      date.getDate()
                    );
                  },
                  interval: 0,
                  rotate: -30,
                  align: "left",
                },
                dataZoom: [
                  {
                    type: "slider",
                    start: 0,
                    end: 7,
                  },
                ],
              },
              yAxis: {
                type: "value",
              },
              tooltip: {
                trigger: "axis",
                axisPointer: {
                  type: "cross",
                },
                formatter: function (params) {
                  const date = new Date(params[0].data[0]);
                  const orderNum = params[0].data[1];
                  return `${date.getFullYear()}-${
                    date.getMonth() + 1
                  }-${date.getDate()}<br>订单数: ${orderNum}`;
                },
              },
              series: [
                {
                  data: this.byDayCountList.map((item) => [
                    new Date(item.sDate),
                    item.orderNum,
                  ]),
                  type: "line",
                },
              ],
            };
            dayLineChart.setOption(dayLineChartOption);
          } else {
            this.$message.error(response.data.message);
          }
        })
        .catch((error) => {
          this.$message.error("无法获取每日数据");
        });
    },
    countByMonth() {
      // this.listLoading = true;
      this.axios
        .get("/api/company/auth/order/countByMonth", {
          params: this.searchList,
        })
        .then((response) => {
          console.log(response);
          if (response.data.code == "200") {
            this.byMonthCountList = response.data.value;
            // 按月数统计
            let monthLineChart = echarts.init(this.$refs.monthLineChart);
            let monthLineChartOption = {
              title: {
                text: "按月统计订单数趋势图",
                left: "center", // 设置标题水平居中
                // textAlign: "center", // 设置标题文字居中
              },
              xAxis: {
                type: "category",
                data: this.byMonthCountList.map((item) => item.sDate),
              },
              yAxis: {
                type: "value",
              },
              tooltip: {
                trigger: "axis",
                triggerOn: "mousemove",
                formatter: function (params) {
                  return params[0].name + "<br>订单数：" + params[0].data;
                },
                axisPointer: {
                  animation: false,
                  type: "line",
                  lineStyle: {
                    color: "#ccc",
                    width: 1,
                    type: "solid",
                  },
                },
              },
              series: [
                {
                  data: this.byMonthCountList.map((item) => item.orderNum),
                  type: "line",
                },
              ],
            };
            monthLineChart.setOption(monthLineChartOption);
          } else {
            this.$message.error(response.data.message);
          }
          // this.listLoading = false;
        })
        .catch((error) => {
          this.$message.error("无法获取每月数据");
          // this.listLoading = false;
        });
    },
    // 获取当前月份的开始时间
    getMonthStartDate() {
      const now = new Date();
      const year = now.getFullYear();
      const month = now.getMonth() + 1;
      const startDate = new Date(`${year}-${month}-01 00:00:00`);
      return startDate;
    },
    // 获取当前月份的结束时间
    getMonthEndDate() {
      const now = new Date();
      const year = now.getFullYear();
      const month = now.getMonth() + 2;
      const endDate = new Date(
        new Date(`${year}-${month}-01 00:00:00`).getTime() - 1
      );
      return endDate;
    },
  },
};
</script>

<style>
.chart-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.chart-item {
  width: 48%;
  height: 280px;
}
</style>
